<?php $this->headScript()->appendFile($this->JS_PATH . 'projectform.js'); ?>
<div id="MainContent">
    <div class="pageerrorcontainer-validator jscript-error-container">
        <div class="error-iterator"></div>
    </div>

    <?php if ($this->succesMessage != ""): ?>
        <div class='pagemcontainer'>
            <p class='pagemessage'>
                <img src="<?php echo $this->IMAGE_PATH; ?>icons/system/accept.gif" class="systemicon" alt="Success" title="Success" />
                <label class='errorlabel'><?php echo $this->succesMessage; ?></label>
            </p>
        </div>
    <?php endif; ?>			

    <?php if (count($this->errorMessageArray) > 0): ?>
        <div class="pageerrorcontainer">
            <?php foreach ($this->errorMessageArray as $erroValue): ?>
                <div class="pageoverflow">
                    <img src="<?php echo $this->IMAGE_PATH; ?>icons/system/stop.gif" class="systemicon" alt="Error" title="Error" />
                    <label class="errorlabel"><?php echo $erroValue; ?></label>
                </div>
            <?php endforeach; ?>				
        </div>
    <?php endif; ?>			
    <div class="clearb">&nbsp;</div>
    <div id="projectform"></div>
    <div class="pagecontainer pageoverflow">
        <div class="pageheader">
            <?php echo $this->mode; ?> Project
            <div class="field-required">* Fields are required </div>
        </div>
        <div style="clear: both;"></div>
        <form id="calculator-form" name="project-form"  enctype="multipart/form-data"  action="" method="post" autocomplete="off">
            <?php echo $this->form->prj_id; ?>
            <input type="hidden" readonly size="60" id="item_count" value="<?php echo count($this->projectReference); ?>" name="item_count">
            <input type="hidden" readonly size="60" id="hdn_delete_prjref_id" value="" name="hdn_delete_prjref_id"/>
            
            <div id="page_content">
                <div class="pageoverflow">
                    <div class="pagetext">Name<span class="error-star">*</span>:</div>
                    <div class="pageinput">
                        <?php echo $this->form->prj_name; ?>
                    </div>
                </div>

                <div class="pageoverflow">
                    <div class="pagetext">Customer<span class="error-star">*</span>:</div>
                    <div class="pageinput">
                        <?php echo $this->form->cus_id; ?>
                        
                        &nbsp;&nbsp;&nbsp;
                    <a target="_blank" href="<?php echo $this->url(array('controller' => 'customer', 'action' => 'form'), null, TRUE) ?>">Add Customer</a>
                    </div>
                </div>

                <div class="pageoverflow">
                    <div class="pagetext">Customer note:</div>
                    <div class="pageinput">
                        <?php echo $this->form->cus_note; ?>
                    </div>
                </div>

                <div class="pageoverflow">
                    <div class="pagetext">Designer in charge<span class="error-star">*</span>:</div>
                    <div class="pageinput">
                        <?php echo $this->form->dsg_id; ?>
                        &nbsp;&nbsp;&nbsp;
                    <a target="_blank" href="<?php echo $this->url(array('controller' => 'designer', 'action' => 'form'), null, TRUE) ?>">Add Designer</a>
                    </div>
                </div>
                
                
                
                <div class="pageoverflow">
                    <p class="pagetext">&nbsp;</p>
                    <p class="pageinput">
                        <a id="create-user" href="#" style="text-decoration:none;">Add Job</a>
                    </p>
                </div>
                
                <div class="<?php echo (count($this->projectReference) > 0 )?"":"display-none"; ?>" id="calculator-table">
                  
                <div class="pageoverflow" >
                    <p class="pagetext">&nbsp;</p>
                    <div class="pageinput">
                        <div class="table-overflow">
                        <table  style="width: 57%; margin: 0px;" class="pagetable">
                            <tbody>
                                <tr>
                                    <th style="height: 30px;">Job Code</th>
                                    <th style="height: 30px;">UOM</th>
                                    <th style="height: 30px;">Contractor</th>
                                    <th style="height: 30px;">Start date</th>
                                    <th style="height: 30px;">Completion date</th>
                                    <th style="height: 30px;">Estimate Day</th>
                                    <th style="height: 30px;">Quantity</th>
                                    <th class="<?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>" style="height: 30px;">Cost Price (RM)</th>
                                    <th style="height: 30px;">Selling Price (RM)</th>
                                    <th style="height: 30px;">Job Remarks</th>
                                    <th style="height: 30px;">Edit</th>
                                    <th style="height: 30px;">Delete</th>
                                    <th class='display-none'>Input</th>
                                </tr>
                                <?php $k = 8000;?>
                            <?php foreach($this->projectReference as $_ref): ?>
                                    <tr class="row2 trid<?php  echo count($this->projectReference)+ $k;?>" trid="<?php  echo count($this->projectReference)+ $k;?>">
                                    <td><?php echo $_ref['job_code'];?></td>
                                    <td><?php echo $_ref['job_uom'];?></td>
                                    <td><?php echo ($this->contractors[$_ref['ctr_id']]['ctr_name']); ?></td>
                                    <td class="job-start-date"><?php echo $startDate = date('Y-m-d' , strtotime($_ref['job_startdate']));?></td>
                                    <td class="job-end-date"><?php echo $endDate = date('Y-m-d' , strtotime($_ref['job_enddate']));?></td>
                                    <td>
                                        
                                        <?php 
                                            $currentDate = date('Y-m-d');
                                            $estimateDay = '';
                                            if ( strtotime($currentDate) >= strtotime($startDate) ) {
                                                if ( strtotime($currentDate) >= strtotime($endDate) ) {
                                                    $estimateDay = 0;
                                                } else {
                                                    $estimateDay = GTL_Common::getDateDifference($endDate,$currentDate);
                                                }
                                            } else {
                                                $estimateDay =  "--";
                                            }
                                        ?>
                                        
                                        <?php echo $estimateDay; ?>
                                        <?php #echo GTL_Common::getDateDifference($endDate,$startDate); ?>
                                        <input type="hidden" class="job_estimate_day_left" value="<?php echo GTL_Common::getDateDifference($endDate, $startDate); ?>"/>
                                    </td>
                                    <td><?php echo $_ref['job_qty'];?></td>
                                    <td class="<?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>"><?php echo $_ref['job_materialcost'];?></td>
                                    <td><?php echo $_ref['job_materialsrp'];?></td>
                                    <td><?php echo nl2br($_ref['job_remark']);?></td>
                                    <td><a href='#' class='edit_modal'>Edit</a></td>
                                    <td><a href='#' class='delete_modal delete_prjref_ids' delete_prjref_ids="<?php echo $_ref['prjref_id'];?>" >Delete</a></td>
                                    
                                    
                                    
                                    <td class='display-none hidden-table'>
                                    <input type='hidden' class='edit_contractor_id'  value='<?php echo $_ref['ctr_id'];?>' name='contractor_id[]'/>
                                    <input type='hidden' class='edit_type' value='job' name='type[]'/>
                                    <input type='hidden' class='edit_product_material_code' value='<?php echo $_ref['job_code'];?>' name='product_material_code[]'/>
                                    <input type='hidden' class='edit_uom' value='<?php echo $_ref['job_uom'];?>' name='uom[]'/>
                                    <input type='hidden' class='edit_qty' value='<?php echo $_ref['job_qty'];?>'  name='qty[]'>
                                    <input type='hidden' class='edit_srp' value='<?php echo $_ref['job_materialsrp'];?>' name='srp[]'/>
                                    <input type='hidden' class='edit_cost' value='<?php echo $_ref['job_materialcost'];?>' name='cost[]'/>
                                    <input type='hidden' class='edit_totalsrp modal_srp' value='<?php echo $_ref['job_totalmaterialsrp'];?>' name='totalsrp[]'/>
                                    <input type='hidden' class='edit_totalcost modal_cost' value='<?php echo $_ref['job_totalmaterialcost'];?>' name='totalcost[]'/>
                                    <input type='hidden' class='edit_inventorylist' value='<?php echo $_ref['job_id'];?>' name='inventorylist[]' />
                                    <input type='hidden' class='edit_job_description' value='<?php echo $_ref['job_remark'];?>' name='job_desc[]' />
                                    <input type='hidden' class='edit_job_startdate'  value='<?php echo date('Y-m-d' , strtotime($_ref['job_startdate']));?>' name='job_startdate[]' />
                                    <input type='hidden' class='edit_job_enddate' value='<?php echo date('Y-m-d' , strtotime($_ref['job_enddate']));?>' name='job_enddate[]' />
                                    <input type='hidden' class='edit_prjref_id' value='<?php echo $_ref['prjref_id'];?>' name='prjref_id[]' />
                                </td>                                        
                                    
                                    
                                    
                                </tr>
                                <?php $k++;?>
                            <?php endforeach; ?>
                                
                                
                                
                            </tbody></table>
                        </div>
                    </div>
                </div>
                
                <div class="pageoverflow">
                    <div class="pagetext">Total days for project:</div>
                    <div class="pageinput">
                        <input type="text" name="prj_totalday" id="prj_totalday" value="<?php echo $this->total_day_diff; ?>" />
                    </div>
                </div>
                
                </div>  
                
                <div class="pageoverflow <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>">
                    <div class="pagetext">Cost price (RM):</div>
                    <div class="pageinput">
                        <?php echo $this->form->prj_costprice; ?>
                    </div>
                </div>

                <div class="pageoverflow">
                    <div class="pagetext">Selling Price (RM):</div>
                    <div class="pageinput">
                        <?php echo $this->form->prj_sellingprice; ?>
                    </div>
                </div>
                
                <div class="pageoverflow <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>">
                    <div class="pagetext">Special Discount (RM):</div>
                    <div class="pageinput">
                        <?php echo $this->form->prj_specialdiscount; ?>
                    </div>
                </div>
                
                <div class="pageoverflow">
                    <div class="pagetext">Renovation Price (RM):</div>
                    <div class="pageinput">
                        <?php echo $this->form->prj_renovationprice; ?>
                    </div>
                </div>
                
                
                <div class="pageoverflow <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>">
                    <p class="pagetext">Profit/Loss margin (RM)</p>
                    <p class="pageinput">
                        <?php echo $this->form->prj_profit_loss_margin; ?>
                    </p>
                </div>
                
                <div class="pageoverflow <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>">
                    <div class="pagetext">Designer commission type:</div>
                    <div class="pageinput">
                        <?php echo $this->form->dsg_commision_type; ?>
                    </div>
                </div>

                <?php 
                    if (array_key_exists('dsg_commision_type',$this->projectData)) {
                        $commisionType = $this->projectData['dsg_commision_type'];
                    } else {
                        $commisionType =  "";
                    }
                    if ($commisionType == 'percentage'){
                        $percentageClass = '';
                    }  else {
                        $percentageClass = 'display-none';
                    }
                ?>
                <div class="pageoverflow <?php echo $percentageClass;?> <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>" id="dsg_commision_percentage-cnt">
                    <div class="pagetext">Designer percentage %<span class="error-star">*</span>:</div>
                    <div class="pageinput">
                        <?php echo $this->form->dsg_commision_percentage; ?>
                    </div>
                </div>
                
                <div class="pageoverflow <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>">
                    <div class="pagetext">Designer commission:</div>
                    <div class="pageinput">
                        <?php echo $this->form->dsg_commision; ?>
                    </div>
                </div>
                
                <div class="calculator">
                    <div class="job-material-cnt">
                        <div class="cal-text-cnt">Image Type</div>
                        <select name="imagetype[]" class="type-list">
                            <?php foreach($this->imageTypeArray as $_key => $_image):?>
                                <option value="<?php echo $_key;?>"><?php echo $_image;?></option>
                            <?php endforeach;?>
                        </select>
                    </div>
                    
                    <div class="job-material-cnt">
                        <div class="cal-text-cnt">Notes</div>
                        <input type="text" length="20" name="prji_notes[]">
                    </div>
                    
                    <div class="job-material-cnt">
                        <div class="cal-text-cnt"> Image</div>
                        <input type="file" class="image_class" name="qni_image[]" id="image_id">
                    </div>

                    <div class="job-material-cnt">
                        <div class="cal-text-cnt"> &nbsp;</div>
                        <a href="#" class="add-cnt"><img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/plus.png" alt="Edit" title="Edit" /></a>
                    </div>
                </div>
                
                <?php if (count($this->projectImages) > 0): ?>
                <div class="pageoverflow">
                    <p class="pagetext"> Project Image</p>
                    <div class="pageinput">
                        <div class="table-overflow">
                        <div class="project-img">
                            <ul>
                            <?php $projectImageChunk = array_chunk($this->projectImages, 3); ?>
                            <?php foreach ($projectImageChunk as $_prjImages): ?>
                                
                                    <?php foreach ($_prjImages as $_projectImages): ?>
                                    <li>
                                        <?php
                                        $thumb_src_path = $this->PUBLIC_PATH . "upload/project/thumb_" . $_projectImages['prji_image'];
                                        $src_path = $this->PUBLIC_PATH . "upload/project/" . $_projectImages['prji_image'];
                                        ?>
                                        <div style="float:left;">
                                            <a style="text-decoration: none;" class="lightbox" href="<?php echo $src_path; ?>">
                                                <img src="<?php echo $thumb_src_path; ?>" height="150" width="150"/>&nbsp;&nbsp;
                                            </a>
                                        </div>
                                        <div style="float:left;">
                                            <a href="#" class="delete-image" imageid="<?php echo $_projectImages['prji_id']; ?>">
                                                <img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/false.gif" alt="Delete" title="Delete" />
                                            </a>
                                        </div>
                                        <div class='clear'></div>
                                        <div style="float:left;">
                                            Type : <b><?php echo $this->imageTypeArray[$_projectImages['prji_type']]; ?></b>
                                        </div>
                                        <div class='clear'></div>
                                        <div style="float:left;">
                                            <?php if ($_projectImages['prji_notes'] != ''): ?>
                                                Notes : <b><?php echo $_projectImages['prji_notes']; ?></b>
                                            <?php else: ?>
                                                &nbsp;
                                            <?php endif; ?>
                                        </div>
                                    </li>
                                    <?php endforeach; ?>
                            <?php endforeach; ?>
                            </ul>
                        </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                
                <div style="clear: both;"></div>
                
                <div class="pageoverflow">
                    <div class="pagetext">Admin Project Notes:</div>
                    <div class="pageinput">
                        <textarea rows="1" cols="60" name="project_notes" id="project_notes"></textarea>
                    </div>
                </div>
                
                
                <?php if ( count($this->projectNotes) > 0 ): ?>
                <div class="pageoverflow">
                    <div class="pagetext"><u>Past Project Notes</u></div>
                    <div class="pagetext">
                        <?php foreach($this->projectNotes as $_notes): ?>
                        
                        
                            <?php
                            if ($_notes['prjn_type'] == '2') {
                                $username = $this->customerArray[$_notes['prjn_lgn_id']];
                            } elseif ($_notes['prjn_type'] == '3') {
                                $username = $this->contractors[$_notes['prjn_lgn_id']]['ctr_name'];
                            } elseif ($_notes['prjn_type'] == '4') {
                                $username = $this->desginerArray[$_notes['prjn_lgn_id']];
                            }
                            ?>
                        
                        <div>
                            <div>
                                    <?php if ($_notes['prjn_type'] == '1'):?>
                                    <u> Myself </u> : on <i><?php echo date('jS F, Y h:i a',strtotime($_notes['prjn_createddate']));?></i>
                                    <?php else: ?>
                                    <u><?php echo ucfirst(strtolower($this->userRoles[$_notes['prjn_type']])); ?>  </u> : <?php echo ($username); ?> on <i><?php echo date('jS F, Y h:i a',strtotime($_notes['prjn_createddate']));?></i>
                                    <?php endif;?>
                            </div>
                            <p>
                                <?php echo $_notes['prjn_notes']; ?>
                            </p>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                
                <div class="pageoverflow">
                    <div class="pagetext">Status<span class="error-star">*</span>:</div>
                    <div class="pageinput">
                        <?php echo $this->form->prj_status; ?>
                    </div>
                </div>

                <div class="pageoverflow">
                    <p class="pagetext">&nbsp;</p>
                    <p class="pageinput">
                        <?php echo $this->form->Save; ?>
                        <?php echo $this->form->Reset; ?>
                    </p>
                </div>
                <div style="clear: both;"></div>
            </div>
        </form>
    </div>
    <p class="pageback">
        <a class="pageback" href="<?php echo $this->url(array('controller' => 'project', 'action' => 'list'), null, TRUE) ?>">&#171; Back to Listing</a>
    </p>
    <div class="clearb"></div>
</div>
<div class="pop-up" id="dialog-form" title="Add Job">
    <p class="validateTips">All form fields are required.</p>
    <fieldset>
        <select id="modal_type" name="modal_type" class="text display-none">
            <option value="job">Job</option>
        </select>
        <label for="modal_code">Job Code</label>
        <input type="text" name="modal_code" id="modal_code" value="" class="text ui-widget-content ui-corner-all" />
        
        <label for="modal_uom">UOM</label>
        <input type="text" name="modal_uom" readonly id="modal_uom" value="" class="text ui-widget-content ui-corner-all" />
        
        <label for="modal_contractor">Contractor</label>
        <select id="modal_contractor" name="modal_contractor" class="text">
            <?php foreach($this->contractors as $_contrator): ?>
                <option value="<?php echo $_contrator['ctr_id'];?>"><?php echo $_contrator['ctr_name'];?></option>
            <?php endforeach;?>
        </select>
        
        <div style='float:left;'>
            <label for="model_startdate">Job start date</label>
            <input type="text" readonly  name="model_startdate" id="model_startdate" value="" class="text ui-widget-content ui-corner-all" />
        </div>
        
        <div style='float:left;'>
            <label for="model_enddate">Job estimate date</label>
            <input type="text" readonly  name="model_enddate" id="model_enddate" value="" class="text ui-widget-content ui-corner-all" />
        </div>
        
        <div class='clear'>&nbsp;</div>
        <label for="model_qty">Quantity</label>
        <input type="text" name="model_qty" id="model_qty" value="" class="text ui-widget-content ui-corner-all" />
        
        <div style='float:left;'>
            <div class="<?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>" >
                <label for="model_costprice">Cost price (RM)</label>
                <input type="text" readonly  name="model_costprice" id="model_costprice" value="" class="text ui-widget-content ui-corner-all" />
            </div>
        </div>
        
        <div style='float:left;'>
            <label for="model_sellingprice">Selling price (RM)</label>
            <input type="text" readonly  name="model_sellingprice" id="model_sellingprice" value="" class="text ui-widget-content ui-corner-all" />
        </div>
        
        <div class='clear'>&nbsp;</div>
        
        <label for="modal_desc">Job remarks</label>
        <textarea name="job_desc[]" rows="6"  cols="38"  id="modal_desc" class="textarea ui-widget-content ui-corner-all" ></textarea>
        
        <input type="hidden" name="model_id" id="model_id" value="" />
        <input type="hidden" name="hdn_model_sellingprice" id="hdn_model_sellingprice" value="" />
        <input type="hidden" name="hdn_model_costprice" id="hdn_model_costprice" value="" />

    </fieldset>
</div>
<div id="calculator-protype" class="display-none">
    <div class="pageoverflow">
        
        
        <div class="calculator">
            <div class="job-material-cnt">
                <div class="cal-text-cnt">Image Type</div>
                <select name="imagetype[]" class="type-list">
                    <?php foreach ($this->imageTypeArray as $_key => $_image): ?>
                        <option value="<?php echo $_key; ?>"><?php echo $_image; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="job-material-cnt">
                <div class="cal-text-cnt">Notes</div>
                <input type="text" length="20" name="prji_notes[]">
            </div>

            <div class="job-material-cnt">
                <div class="cal-text-cnt"> Image</div>
                <input type="file" class="image_class" name="qni_image[]" id="image_id">
            </div>

            <div class="job-material-cnt">
                <div class="cal-text-cnt"> &nbsp;</div>
                <a href="#" class="add-cnt"><img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/plus.png" alt="Edit" title="Edit" /></a>
            </div>
            
            <div class="job-material-cnt">
                <div class="cal-text-cnt"> &nbsp;</div>
                <a href="#" class="remove-cnt"><img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/minus.png" alt="Edit" title="Edit" /></a>
            </div>
            
        </div>
        
    </div>
</div>   
<script>

$(function() {
    
    
    
    //Variable Initialization
    var modal_type = $("#modal_type"),
            modal_code = $("#modal_code"),
            modal_uom = $("#modal_uom"),
            model_qty = $("#model_qty"),
            model_sellingprice = $("#model_sellingprice"),
            model_costprice = $("#model_costprice"),
            model_id = $("#model_id"),
            hdn_model_sellingprice = $("#hdn_model_sellingprice"),
            hdn_model_costprice = $("#hdn_model_costprice"),
            model_startdate = $('#model_startdate'),
            modal_contractor = $('#modal_contractor'),
            model_enddate = $('#model_enddate'),
            modal_desc = $('#modal_desc'),
            allFields = $([]).add(modal_type).add(modal_code).add(modal_uom).add(model_qty).add(model_sellingprice).add(model_costprice).add(model_id).add(hdn_model_sellingprice).add(hdn_model_costprice).add(model_startdate).add(modal_contractor).add(model_enddate).add(modal_desc),
            tips = $(".validateTips");
            
        
        
        function nl2br (str, is_xhtml) {
            var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
            return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
        }
                    
    
    //Form Validation
    $('#calculator-form').submit(function() {
        
        $('.jscript-error-container').html('');
        //Remove the error class
        $("#calculator-form :input").removeClass('error');

        //Hide Error Container and remove the contents from it
        $('.jscript-error-container').html('');
        $('.jscript-error-container').hide();
        
        //Initialize error container
        var errMessage = [];
        
        var name = $('#prj_name').val();
        name = jQuery.trim(name);
        if (name === '') {
            errMessage.push('Please enter project name');
            $('#prj_name').addClass('error');
            $('#prj_name').focus();
        }
        
        
        var cus_id = $('#cus_id').val();
        cus_id = jQuery.trim(cus_id);
        if (cus_id === '') {
            errMessage.push('Please select customer');
            $('#cus_id').addClass('error');
            $('#cus_id').focus();
        }
        
        var dsg_id = $('#dsg_id').val();
        dsg_id = jQuery.trim(dsg_id);
        if (dsg_id === '') {
            errMessage.push('Please select designer');
            $('#dsg_id').addClass('error');
            $('#dsg_id').focus();
        }
        
        
        var item_count = $('#item_count').val();
        item_count = parseInt(item_count);
        if (item_count <= 0) {
            errMessage.push('Please add atleast one job');
        }
        
            
        var prj_status = $('#prj_status').val();
        prj_status = jQuery.trim(prj_status);
        if (prj_status === '') {
            errMessage.push('Please select status');
            $('#prj_status').addClass('error');
            $('#prj_status').focus();
        }
        
        //Percentage Validation
        var dsg_commision_percentage = $('#dsg_commision_percentage').val();
        dsg_commision_percentage = jQuery.trim(dsg_commision_percentage);
        if (dsg_commision_percentage !== '') {
            var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
            numberResult = numberPattern.test(dsg_commision_percentage);
            if (numberResult === false) {
                errMessage.push('Please enter designer commision percentage in numeric format');
                $('#dsg_commision_percentage').addClass('error');
                $('#dsg_commision_percentage').focus();
            }
        }
        
        
        //Commision Validation
        var dsg_commision = $('#dsg_commision').val();
        dsg_commision = jQuery.trim(dsg_commision);
        if (dsg_commision !== '') {
            var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
            numberResult = numberPattern.test(dsg_commision);
            if (numberResult === false) {
                errMessage.push('Please enter designer commision in numeric format');
                $('#dsg_commision').addClass('error');
                $('#dsg_commision').focus();
            }
        }
        
        
       //Special Discount Numerical Validation 
        var prj_specialdiscount = $('#prj_specialdiscount').val();
        prj_specialdiscount = jQuery.trim(prj_specialdiscount);
        if (prj_specialdiscount !== '') {
            var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
            numberResult = numberPattern.test(prj_specialdiscount);
            if (numberResult === false) {
                errMessage.push('Please enter special discount in numeric format');
                $('#prj_specialdiscount').addClass('error');
                $('#prj_specialdiscount').focus();
            }
        }
        
        //Special Discount Numerical Validation 
        var prj_renovationprice = $('#prj_renovationprice').val();
        prj_renovationprice = jQuery.trim(prj_renovationprice);
        if (prj_renovationprice !== '') {
            var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
            numberResult = numberPattern.test(prj_renovationprice);
            if (numberResult === false) {
                errMessage.push('Please enter renovation price in numeric format');
                $('#prj_renovationprice').addClass('error');
                $('#prj_renovationprice').focus();
            }
        }
        
        
        
        
        //Selling price Numerical Validation 
        var prj_sellingprice = $('#prj_sellingprice').val();
        prj_sellingprice = jQuery.trim(prj_sellingprice);
        if (prj_sellingprice !== '') {
            var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
            numberResult = numberPattern.test(prj_sellingprice);
            if (numberResult === false) {
                errMessage.push('Please enter valid renovation cost in numeric format');
                $('#prj_sellingprice').addClass('error');
                $('#prj_sellingprice').focus();
            }
        }
        
         //Image validation
        var imageCounter = 0;
        $('#calculator-form').find('.image_class').each(function() {
            if ($(this).val() !== '' ) {
                var ext = $(this).val().split('.').pop().toLowerCase();
                if($.inArray(ext, ['gif','png','jpg','jpeg']) === -1) {
                    $(this).addClass('error');
                    $(this).focus();
                    imageCounter++;
                }

            }
        });
        if (imageCounter > 0) {
            errMessage.push('Please select image with valid extension');
        }
        
           
        if (errMessage.length > 0) {
            var content = "";
            $.each(errMessage, function(index,value){
                content += "<div class='pageoverflow'><label class='errorlabel'>"+value+"</label></div>";
            });
            $('.jscript-error-container').html(content);
            $('.jscript-error-container').show();
            return false;
        } else {
            
            
            //Calculate final srp and cost price
            calculateTotalModalCostPrice();
            calculateTotalModalSellingPrice();
            calculateTotalProfitLoss();
            calculateTotalDayofProject();
            return true;
        }
            
    });
    
    
    $('body').delegate('.edit_modal', 'click', function() {
            var content = $(this);
            var obj = $(content.parents('tr').find('.hidden-table'));
            var editTrId = content.parents('tr').attr('trid');
            var edit_type = obj.find('.edit_type').val();
            var edit_product_material_code =obj.find('.edit_product_material_code').val();
            var edit_uom = obj.find('.edit_uom').val();
            var edit_qty = obj.find('.edit_qty').val();
            var edit_srp = obj.find('.edit_srp').val();
            var edit_cost = obj.find('.edit_cost').val();
            var edit_totalsrp = obj.find('.edit_totalsrp').val();
            var edit_totalcost = obj.find('.edit_totalcost').val();
            var edit_inventorylist = obj.find('.edit_inventorylist').val();
            var edit_job_description = obj.find('.edit_job_description').val();
            var edit_contractor_id = obj.find('.edit_contractor_id').val();
            var edit_prjref_id = obj.find('.edit_prjref_id').val();
            var edit_job_startdate = obj.find('.edit_job_startdate').val();
            var edit_job_enddate = obj.find('.edit_job_enddate').val();
            
            $('#modal_type').val(edit_type);
            $('#modal_code').val(edit_product_material_code);
            $('#modal_uom').val(edit_uom);
            $('#modal_type').val(edit_type);
            $('#modal_contractor').val(edit_contractor_id);
            $('#model_startdate').val(edit_job_startdate);
            $('#model_enddate').val(edit_job_enddate);
            $('#model_qty').val(edit_qty);
            $('#model_costprice').val(edit_totalcost);
            $('#model_sellingprice').val(edit_totalsrp);
            $('#modal_desc').val(edit_job_description);
            $('#model_id').val(edit_inventorylist);
            $('#hdn_model_sellingprice').val(edit_srp);
            $('#hdn_model_costprice').val(edit_cost);
            var Linkobj = {};
            Linkobj['type'] = 'edit';
            Linkobj['trid'] = editTrId;
            Linkobj['prjref_id'] = edit_prjref_id;
            $( "#dialog-form" ).dialog({ title: "Edit Job" });
            $( "#dialog-form" ).data('link', Linkobj).dialog( "open" );
        });
    
    
    
    
    
    
    
    //Event Register of the Selling Price 
    $('#prj_sellingprice').on('keyup focusout blur', function() {
        //Validation for the Total Selling price as number
        var totalSellingprice = $('#prj_sellingprice').val();
        totalSellingprice = jQuery.trim(totalSellingprice);
        var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
        numberResult = numberPattern.test(totalSellingprice);
        if (numberResult === false) {
            return false;
        } else if ($('#prj_costprice').val() === '' ) {
            return false;
        } else {
            calculateTotalProfitLoss();
            
            //Trigger Percentage change incase percentage changes
            if ($('#dsg_commision_percentage').val() !== '') {
                $('#dsg_commision_percentage').trigger('keyup');
            }
            
        }
    });  
    
    //Event Register of the Special Discount
    $('#prj_specialdiscount').on('keyup focusout blur', function() {
        //Validation for the Total Selling price as number
        var discount = $('#prj_specialdiscount').val();
        discount = jQuery.trim(discount);
        
        if (discount === '' ) {
            $('#prj_renovationprice').val($('#prj_sellingprice').val());
            return false;
        }
        
        var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
        numberResult = numberPattern.test(discount);
        if (numberResult === false) {
            return false;
        } else if ($('#prj_costprice').val() === '' ) {
            return false;
        } else {
            var prj_sellingprice = $('#prj_sellingprice').val();
            prj_sellingprice = jQuery.trim(prj_sellingprice);
            var renovationCost = prj_sellingprice - discount;
            $('#prj_renovationprice').val(renovationCost.toFixed(2));
            calculateTotalProfitLoss();
            //Trigger Percentage change incase percentage changes
            if ($('#dsg_commision_percentage').val() !== '') {
                $('#dsg_commision_percentage').trigger('keyup');
            }
            
        }
    });  
    
    
    
    //Event Register of the Quantity in the Modal Box
    $('#model_qty').on('keyup focusout blur', function() {
        checkQuantityValid(model_qty);
    });
    
    //Update and animation show of error in the modal box fields
    function updateTips(t) {
        tips.text(t).addClass("ui-state-highlight");
        setTimeout(function() {
            tips.removeClass("ui-state-highlight", 1500);
        }, 700);
    }
    
    function strtotime(date) {
        var d = Date.parse(date) / 1000;
        return d;
    }
    
    //Calculate the total days for the project 
    //Calculate final cost price
    function calculateTotalDayofProject() {
        var totalDay = 0;
        var jobStartArray = [];
        var jobEndArray = [];
        
        var min_start_date = strtotime('2037-12-12');
        
        var i = 0;
        var startindex = 0;
        $('.job-start-date').each(function() {
            if (jQuery.trim($(this).html()) !== '') {
                jobStartArray.push( jQuery.trim($(this).html()) );
                start_date = jQuery.trim($(this).html());
                if (min_start_date > strtotime(start_date)) {
                    min_start_date = strtotime(start_date);
                    startindex = i;
                }
            }
            i++;
        });
        
        
        var j = 0;
        var max_index = 0;
        var max_end_date = 0;
        
        $('.job-end-date').each(function() {
            if (jQuery.trim($(this).html()) !== '') {
                jobEndArray.push( jQuery.trim($(this).html()) );
                end_date = jQuery.trim($(this).html());
                if (max_end_date < strtotime(end_date)) {
                    max_end_date = strtotime(end_date);
                    max_index = j;
                }
            }
            j++;
        });
        
        min_start_date = jobStartArray[startindex];
        max_end_date = jobEndArray[max_index];
        
        var diff = calculateDayDiffBetweenDates(new Date(max_end_date),new Date(min_start_date));
        
        /*
        $('.job_estimate_day_left').each(function() {
            if (jQuery.trim($(this).val()) !== '') {
                totalDay += parseInt(jQuery.trim($(this).val()));
            }
        });
        */
        $('#prj_totalday').val(diff);
    }
    
    //Calculate final cost price
    function calculateTotalModalCostPrice() {
        var costprice = 0.00;
        $('.modal_cost').each(function() {
            if (jQuery.trim($(this).val()) !== '') {
                costprice += parseFloat(jQuery.trim($(this).val()));
            }
        });
        $('#prj_costprice').val(costprice.toFixed(2));
    }
    
    //Calculate profit and loss margin
    function calculateTotalProfitLoss() {
        var prj_profit_loss_margin = 0.00;
        var sellingPrice = parseFloat(jQuery.trim($('#prj_sellingprice').val())).toFixed(2);
        var costPrice = parseFloat(jQuery.trim($('#prj_costprice').val())).toFixed(2);
        prj_profit_loss_margin = sellingPrice - costPrice;
        
        //Special Discount Numerical Validation 
        var prj_specialdiscount = $('#prj_specialdiscount').val();
        prj_specialdiscount = jQuery.trim(prj_specialdiscount);
        if (prj_specialdiscount !== '') {
            var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
            numberResult = numberPattern.test(prj_specialdiscount);
            if (numberResult === true) {
                //Calculatir over here     
                costPrice = parseFloat(jQuery.trim($('#prj_costprice').val())).toFixed(2);
                var prj_renovationprice = parseFloat(jQuery.trim($('#prj_renovationprice').val())).toFixed(2);
                prj_profit_loss_margin = prj_renovationprice - costPrice;
            }
        } else {
            sellingPrice = parseFloat(jQuery.trim($('#prj_sellingprice').val())).toFixed(2);
            costPrice = parseFloat(jQuery.trim($('#prj_costprice').val())).toFixed(2);
            prj_profit_loss_margin = sellingPrice - costPrice;
        }
        
        prj_profit_loss_margin = prj_profit_loss_margin.toFixed(2);
        $('#prj_profit_loss_margin').val(prj_profit_loss_margin);
        
    }
    
    //Calculate final selling price
    function calculateTotalModalSellingPrice() {
        var sellingprice = 0.00;
        $('.modal_srp').each(function() {
            if (jQuery.trim($(this).val()) !== '') {
                sellingprice += parseFloat(jQuery.trim($(this).val()));
            }
        });
        
        $('#prj_sellingprice').val(sellingprice.toFixed(2));
        
        //Calculate Renovation price based on the 
        if ($('#prj_specialdiscount').val() === '') {
            $('#prj_renovationprice').val(sellingprice.toFixed(2));
        } else {
            $('#prj_specialdiscount').trigger('blur');
        }
        
        
        
    }
    
    function calculateDayDiffBetweenDates(startDateObj, endDateObj) {
        var timeDiff = Math.abs(endDateObj.getTime() - startDateObj.getTime());
        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
        return diffDays;
    }
    
    
    //Validation of the Quantity
    function checkQuantityValid(o) {
        var model_qty = $('#model_qty').val();
        //Validation for the Quantity as integer
        var pattern = /^\d+$/;
        result = pattern.test(model_qty);
        if (result === false) {
            o.addClass("ui-state-error");
            updateTips("Quantity should be a number only");
            return false;
        } else if ($('#model_id').val() === ''){
            o.addClass("ui-state-error");
            updateTips("Please enter product or item code before quantity");
            return false;
        } else {
            model_qty = jQuery.trim(model_qty);
            var quantity = parseInt(model_qty);
            
            var costPrice = $('#hdn_model_costprice').val();
            costPrice = parseFloat(jQuery.trim(costPrice)).toFixed(2);
            
            var sellingprice = $('#hdn_model_sellingprice').val();
            sellingprice = parseFloat(jQuery.trim(sellingprice)).toFixed(2);
            
            var totalCost = quantity * costPrice;
            var totalSrp = quantity * sellingprice;
            
            $('#model_costprice').val(totalCost.toFixed(2));
            $('#model_sellingprice').val(totalSrp.toFixed(2));
            return true;
        }
    }
    
    //Validation of the job start date
    function checkJobStartdateValid(o) {
        var modal_startdate = $('#model_startdate').val();
        if ((modal_startdate === "") || (typeof modal_startdate === "undefined")) {
            o.addClass("ui-state-error");
            updateTips("Please enter job start date");
            return false;
        } else {
            return true;
        }
    }
    
    //Validation of the job end date
    function checkJobEnddateValid(o) {
        var modal_enddate = $('#model_enddate').val();
        if ((modal_enddate === "") || (typeof modal_enddate === "undefined")) {
            o.addClass("ui-state-error");
            updateTips("Please enter job estimate complete date");
            return false;
        } else {
            return true;
        }
    }
    
    
    //Validation of the product
    function checkProductItemValid(o) {
        var model_id = $('#model_id').val();
        if ((model_id === "") || (typeof model_id === "undefined")) {
            o.addClass("ui-state-error");
            updateTips("Please enter atleast one product or item code");
            return false;
        } else {
            return true;
        }
    }
    //Event registration for the button and dialog open
    $( "#create-user" ).button();
            
            
    $( "#create-user" ).click(function() {
        
        
    var Linkobj = {};
            Linkobj['type'] = 'add';
            Linkobj['trid'] = '';
            Linkobj['prjref_id'] = '';
            $( "#dialog-form" ).dialog({ title: "Add Job / Product" });
            $( "#dialog-form" ).data('link', Linkobj) 
                    .dialog( "open" );  
    });
    
    var deleteQnrIdArray = [];
    //Event registration for the delete of the job and products
    $('body').delegate('.delete_modal', 'click', function() {
        
        //If the delete is done with the existing than project reference than delete id are added in the hidden variable
        if ($(this).hasClass('delete_prjref_ids')) {
            deleteQnrIdArray.push($(this).attr('delete_prjref_ids'));
            $('#hdn_delete_prjref_id').val(deleteQnrIdArray.toString());
        }
        
    
        $(this).parents('tr').remove();
        
        //Calculate final srp and cost price
        calculateTotalModalCostPrice();
        calculateTotalModalSellingPrice();
        calculateTotalProfitLoss();
        calculateTotalDayofProject();

        
        //Substract the itemcount to 1 once table row is added
        var item_count  = $('#item_count').val();
        item_count = parseInt(item_count);
        if (item_count > 0 ) {
            item_count = parseInt(item_count) - 1;
            $('#item_count').val(item_count);
        }
        //Hide the blank table header
        if (item_count === 0) {
            $('#calculator-table').hide();
        }
        return false;
    });
    
    
    
    //Event registration for the dialog box
    $("#dialog-form").dialog({
        autoOpen: false,
        height: 570,
        width: 390,
        modal: true,
        buttons: {
            "Add": function() {
                //Bool to check the fields validation of the modal box
                var bValid = true;
                //Remove all error form the modal box
                allFields.removeClass("ui-state-error");
                
                //Validation of the modal fields
                bValid = bValid && checkProductItemValid(modal_code);
                bValid = bValid && checkJobStartdateValid(model_startdate);
                bValid = bValid && checkJobEnddateValid(model_enddate);
                bValid = bValid && checkQuantityValid(model_qty);
                
                if (bValid) {
                    
                    
                    var startDateObj = $( "#model_startdate" ).datepicker( "getDate" );
                    var endDateObj = $( "#model_enddate" ).datepicker( "getDate" );
                    
                    var startDate = $( "#model_startdate" ).val();
                    var endDate = $( "#model_enddate" ).val();
                    
                    //alert(startDate);
                    //alert(endDate);
                    
                    
                    //var timeDiff = Math.abs(endDateObj.getTime() - startDateObj.getTime());
                    //var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
                    var currentDate = '<?php echo date('Y-m-d')?>';
                    estimateDay = '';
                    if ( strtotime(currentDate) >= strtotime(startDate) ) {
                        if ( strtotime(currentDate) >= strtotime(endDate) ) {
                            estimateDay = 0;
                        } else {
                            estimateDay = calculateDayDiffBetweenDates(new Date(endDate),new Date(currentDate));
                        }
                    } else {
                        estimateDay =  "--";
                    }
                    
                    
                    //var diffDays = calculateDayDiffBetweenDates(startDateObj,endDateObj);
                    var diffDays = estimateDay;
                    
                    //Show the table
                    $('#calculator-table').removeClass('display-none');
                    var ucFirsttype = modal_type.val().charAt(0).toUpperCase() + modal_type.val().slice(1);
                    //Append the tr to the table
                    
                    var classAdmin= '<?php echo ($this->user->role == "ADMIN")?"":"display-none"; ?>';
                    
                        var path = $(this).data('link'); 
                        var prjrefTd  = '';
                        if (path.type === 'add') {
                            //Add the itemcount to 1 once table row is added
                            var item_count = $('#item_count').val();
                            item_count = parseInt(item_count) + 1;
                            $('#item_count').val(item_count);
                            prjref_id = "<input type='hidden' class='edit_prjref_id' value='' name='prjref_id[]' />";
                        }
                        prjrefTd = "<input type='hidden' class='edit_prjref_id' value='" + path.prjref_id + "' name='prjref_id[]' />";
                        var classtrid = "trid" + item_count;
                        var contrator_text = $("#modal_contractor option[value='"+modal_contractor.val()+"']").text();
                    var tdRow = "<td>" + modal_code.val() + "</td>" +
                            "<td>" + modal_uom.val() + "</td>" +
                            "<td>" + contrator_text + "</td>" +
                            "<td class='job-start-date' >" + model_startdate.val() + "</td>" +
                            "<td class='job-end-date' >" + model_enddate.val() + "</td>" +
                            "<td>" + diffDays + "<input type='hidden' class='job_estimate_day_left' value='"+diffDays+"'/>" +"</td>" +
                            "<td>" + model_qty.val() + "</td>" +
                            "<td class='"+ classAdmin +"' >" + hdn_model_costprice.val() + "</td>" +
                            "<td>" + hdn_model_sellingprice.val() + "</td>" +
                            "<td>" + nl2br(modal_desc.val()) + "</td>" +
                            "<td><a href='#' class='edit_modal'>Edit</a></td>" +
                            "<td><a href='#' class='delete_modal'>Delete</a></td>" +
                            "<td class='display-none hidden-table'>" +
                            "<input type='hidden' class='edit_contractor_id'   value='" + modal_contractor.val() + "' name='contractor_id[]'/>" +
                            "<input type='hidden' class='edit_uom'  value='" + modal_uom.val() + "' name='uom[]'/>" +
                            "<input type='hidden' class='edit_type' value='" + modal_type.val() + "' name='type[]'/>" +
                            "<input type='hidden' class='edit_product_material_code'  value='" + modal_code.val() +"' name='product_material_code[]'/>" +
                            "<input type='hidden' class='edit_qty'  value='"+ model_qty.val() +"'  name='qty[]'>" + 
                            "<input type='hidden' class='edit_srp'  value='" + hdn_model_sellingprice.val() + "' name='srp[]'/>" +
                            "<input type='hidden' class='edit_cost' value='" + hdn_model_costprice.val() + "' name='cost[]'/>" +
                            "<input type='hidden' value='" + model_sellingprice.val() + "' class='edit_totalsrp modal_srp'  name='totalsrp[]'/>" +
                            "<input type='hidden' value='" + model_costprice.val() + "' class='edit_totalcost modal_cost' name='totalcost[]'/>" +
                            "<input type='hidden' class='edit_inventorylist'  value='" + model_id.val() + "' name='inventorylist[]' />" +
                            "<input type='hidden' class='edit_job_startdate'  value='" + model_startdate.val() + "' name='job_startdate[]' />" +
                            "<input type='hidden' class='edit_job_enddate' value='" + model_enddate.val() + "' name='job_enddate[]' />" +
                            "<input type='hidden' class='edit_job_description' value='" + modal_desc.val() + "' name='job_desc[]' />" +
                            prjrefTd + 
                            "</td>";
                    
                            var trRow = "<tr class='row2 "+classtrid+"' trid="+item_count +" >" + tdRow + "</tr>";
                            
                        if (path.type === 'edit') {
                            var trid = path.trid;
                            var tableId = 'trid'+ trid;
                            $('.'+ tableId).html('');
                            $('.'+ tableId).html(tdRow);
                        } else {
                            $(".pagetable").append(trRow);
                        }
                            
                    //Calculate the final srp and cost price   
                    calculateTotalModalSellingPrice();
                    calculateTotalModalCostPrice();
                    calculateTotalDayofProject();

                    //Calculate the profit
                    calculateTotalProfitLoss();
                    
                    //Show the table
                    $('#calculator-table').show();
        
                    
                    $(this).dialog("close");
                }
            },
            Cancel: function() {
                $(this).dialog("close");
            }
        },
        close: function() {
            allFields.val("").removeClass("ui-state-error");
        }
    });
    
    //Initialization of the autocomplete 
    jQuery("#modal_code").autocomplete({
        source: function(request, response) {
            var postData = {};
            postData['search'] = request.term;
            postData['type'] = $("#modal_type").val();
            $.ajax({
                url: BASE_PATH + '/project/generatejobsearch',
                dataType: "json",
                type: 'POST',
                data: postData,
                success: function(data) {
                    response(
                            $.map(data, function(item) {
                                return {
                                    id: item.id,
                                    label: item.code,
                                    value: item.code,
                                    uom: item.uom,
                                    cost_price: item.costprice,
                                    srp_price: item.srpprice
                                };
                            })
                    );
                }
            });
        },
        select: function(event, ui) {
            $('#model_qty').val('1');
            $('#modal_code').val(ui.item.code);
            $('#modal_uom').val(ui.item.uom);
            $('#model_costprice').val(ui.item.cost_price);
            $('#model_sellingprice').val(ui.item.srp_price);
            $('#model_id').val(ui.item.id);
            $('#hdn_model_costprice').val(ui.item.cost_price);
            $('#hdn_model_sellingprice').val(ui.item.srp_price);
        },
        minLength: 1
    });
});
</script>